<template>
  <div class="login-box">
    <div class="login-info-box">
      <div class="login-info-img-box">
        <img src="@a/imgs/login-form-img.png" alt="">
      </div>
      <div class="login-info-form-box">
        <div class="head-box">
          <img src="../../assets/imgs/logo2.png" alt="">
          <h1 class="login-title">您好！欢迎使用管理平台</h1>
        </div>
        <div class="login-form">
          <el-form ref="loginFormRef" style="margin-top:20px" :model="loginForm" :rules="loginRules">
            <el-form-item prop="account">
              <el-input v-model="loginForm.account" maxlength="11" clearable placeholder="请输入登录的手机号码" />
            </el-form-item>
            <el-form-item prop="password" style="margin-top:20px">
              <el-input v-model="loginForm.password" type="password" clearable placeholder="请输入密码" />
            </el-form-item>
            <el-form-item prop="code">
              <el-input class="append" v-model="loginForm.code" placeholder="请输入验证码" @keypress.enter="login">
                <template #append><img :src="codeImgUrl" alt @click="getVerificationCode" /></template>
              </el-input>
            </el-form-item>
          </el-form>
          <div class="pass-box">
            <el-checkbox v-model="isRemember" @change="isRemChange">记住密码</el-checkbox>
            <span class="forget" @click="forgetPass">忘记密码</span>
          </div>
          <div class="login-btn" @click="login">立即登录</div>
        </div>
        <!-- <div class="registered">还未开店？<span @click="registered">注册店铺</span></div> -->
      </div>
    </div>
    <!-- <div class="record-box" @click="toBeian">
      <img src="@/assets/imgs/gh.png" alt="">
      <span>鲁公网安备 37010402001439号、鲁ICP备2023025063号</span>
    </div> -->
  </div>
</template>

<script>
import { onMounted, reactive, ref, toRefs } from 'vue'
import hexMD5 from "@/utils/md5.min.js"
import api from './api'
import { successDeal, warningDeal, getExplorerInfo } from '@/utils/utils'
import { Base64 } from 'js-base64'
import { useRouter } from 'vue-router'
export default {
  setup() {
    const router = useRouter()

    const loginFormRef = ref(null)

    const state = reactive({
      codeImgUrl: null,
      isRemember: false,
      loginForm: {
        account: null,
        password: null,
      },
      loginRules: {
        account: [
          { required: true, message: '请输入登录手机号', trigger: 'blur' },
          {
            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/, message: '手机号码格式不正确', trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入登录密码', trigger: 'blur' },
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
        ]
      },
    })

    function isRemChange(e) {
      if (!e) {
        window.localStorage.removeItem('JHH_loginInfo')
      }
      window.localStorage.setItem('JHH_isRemember', JSON.stringify(e))
    }

    function login() {
      loginFormRef.value.validate(async (valid, fields) => {
        if (!valid) return
        if (state.isRemember) {
          const obj = {
            account: encryption(state.loginForm.account),
            password: encryption(state.loginForm.password),
          }
          window.localStorage.setItem('JHH_loginInfo', JSON.stringify(obj))
        }
        const myObj = {
          account: state.loginForm.account,
          password: hexMD5(state.loginForm.password),
          key: state.loginForm.key,
          code: state.loginForm.code,
        }
        await api.companyLogin(myObj).then(async res => {
          if (res.code == '200') {
            window.localStorage.setItem('JHH_USER_TOKEN', res.data.token)
            window.localStorage.setItem('JHH_USER_INFO', JSON.stringify(res.data))
            window.localStorage.setItem('JHH_USER_AUTHOR', JSON.stringify({ Authorization: `${res.data.userId},'',${getExplorerInfo()},3,20,''` }))
            await getUserMenu()
            router.push({ path: '/home' })
          } else {
            warningDeal(res.msg)
          }
        }).catch(err => {
          console.log(err)
          getVerificationCode()
        })
      })
    }

    async function getUserMenu() {
      await api.userMenu().then(res => {
        if (res.code == '200') {
          window.localStorage.setItem('JHH_USER_MENU', JSON.stringify(res.data.list))
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function getVerificationCode() {
      api.authCaptcha().then(res => {
        state.loginForm.code = null
        state.loginForm.key = res.data.key;
        state.codeImgUrl = res.data.img;
      })
    }

    //注册
    function registered() {
      router.push({ path: '/registered' })
    }

    //忘记密码
    function forgetPass() {
      router.push({ path: '/forgetPass' })
    }

    //加密
    function encryption(pass) {
      const key = Base64.encode('wanna')
      const myPass = Base64.encode(pass)
      const bpass = Base64.encode(myPass + key)
      return bpass
    }

    //解密
    function decryption(pass) {
      const key = Base64.encode('wanna')
      const myPass = Base64.decode(pass)
      const apass = myPass.split(key)[0]
      const bpass = Base64.decode(apass)
      return bpass
    }

    function toBeian() {
      window.open('http://beian.miit.gov.cn', '_blank')
    }

    onMounted(() => {
      window.localStorage.removeItem('JHH_USER_TOKEN')
      window.localStorage.removeItem('JHH_USER_INFO')
      window.localStorage.removeItem('JHH_USER_AUTHOR')
      window.localStorage.removeItem('JHH_USER_MENU')
      const isRem = JSON.parse(window.localStorage.getItem('JHH_isRemember'))
      const loginInfo = JSON.parse(window.localStorage.getItem('JHH_loginInfo'))
      if (isRem && loginInfo) {
        state.loginForm = {
          account: decryption(loginInfo.account),
          password: decryption(loginInfo.password),
        }
        state.isRemember = isRem || false
      }
      getVerificationCode()
      setTimeout(() => {
        import('@/views/welcome')
      }, 100);
    })

    return {
      ...toRefs(state),
      loginFormRef,
      isRemChange,
      forgetPass,
      login,
      getVerificationCode,
      registered,
      toBeian,
    }
  }
}
</script>

<style lang="scss" scoped>
.login-box {
  width: 100%;
  height: 100%;
  background-color: #336feb;
  display: flex;
  .login-info-box {
    // width: 70%;
    // height: 57%;
    background-color: #ffffff;
    border-radius: 5px;
    margin: auto;
    display: flex;
    align-items: center;
    overflow: hidden;
    box-sizing: border-box;
    padding: 50px;
    .login-info-img-box {
      width: 40%;
      height: 100%;
      display: flex;
      > img {
        width: 100%;
        margin: auto;
      }
    }
    .login-info-form-box {
      margin-left: 10%;
      width: 45%;
      height: 100%;
      box-sizing: border-box;
      display: flex;
      flex-flow: column;
      justify-content: center;
      gap: 20px;
      .head-box {
        display: flex;
        align-items: flex-end;
        > img {
          max-height: 100px;
        }
      }
      .login-title {
        font-size: 24px;
        flex-shrink: 0;
      }
      .login-form {
        .pass-box {
          color: #333333;
          font-size: 14px;
          display: flex;
          justify-content: space-between;
          align-items: center;
          .forget {
            cursor: pointer;
          }
        }
        .login-btn {
          width: 100%;
          text-align: center;
          background-color: #0081ff;
          border-radius: 3px;
          color: #ffffff;
          padding: 8px 0;
          font-size: 14px;
          cursor: pointer;
          margin-top: 10px;
        }
      }
      .registered {
        text-align: center;
        > span {
          color: #1b63e9;
          cursor: pointer;
        }
      }
    }
  }
}
.record-box {
  position: fixed;
  bottom: calc(50% - 300px);
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  gap: 5px;
  color: #d8d8d8;
}
</style>